<template>
  <ContentWrap ref="form">
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="班级名称" prop="classesName">
        <el-input
          v-model="queryParams.classesName"
          placeholder="请输入班级名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="班级编码" prop="classesCode">
        <el-input
          v-model="queryParams.classesCode"
          placeholder="请输入班级编码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="学校名称" prop="schoolId">
        <el-select
          v-model.trim="queryParams.schoolId"
          clearable
          filterable
          placeholder="请选择学校"
          @change="changeSchool"
          class="!w-240px"
        >
          <el-option
            v-for="item in schoolList"
            :key="item.id"
            :label="item.schoolName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="机构名称" prop="collegeId">
        <el-select
          v-model.trim="queryParams.collegeId"
          clearable
          filterable
          placeholder="请选择机构"
          @change="changeCollege"
          :disabled="!queryParams.schoolId"
          class="!w-240px"
        >
          <el-option
            v-for="item in collegeList"
            :key="item.id"
            :label="item.collegeName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="专业名称" prop="majorId">
        <el-select
          v-model.trim="queryParams.majorId"
          clearable
          filterable
          placeholder="请选择专业"
          @keyup.enter="handleQuery"
          :disabled="!queryParams.schoolId"
          class="!w-240px"
        >
          <el-option
            v-for="item in majorList"
            :key="item.id"
            :label="item.majorName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="年级" prop="grade">
        <el-select v-model="queryParams.grade" placeholder="请选择状态" clearable class="!w-240px">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CMIS_GRADE_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button type="primary" @click="openForm('create')" v-hasPermi="['cmis:classes:create']">
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="warning"
          plain
          @click="onOpenBatchImport"
          v-hasPermi="['cmis:classes:import']"
        >
          <Icon icon="ep:upload" class="mr-5px" />
          导入
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['cmis:classes:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button type="danger" @click="handleDeleteMulti" v-hasPermi="['cmis:classes:delete']">
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap :setPadding="false">
    <el-table
      v-loading="loading"
      :data="list"
      @selection-change="selectionChange"
      stripe
      :max-height="tableHeight"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="班级名称" prop="classesName" show-overflow-tooltip />
      <el-table-column label="班级编码" prop="classesCode" show-overflow-tooltip />
      <el-table-column label="学校名" prop="schoolName" show-overflow-tooltip />
      <el-table-column label="机构名称" prop="collegeName" show-overflow-tooltip />
      <el-table-column label="专业名称" prop="majorName" show-overflow-tooltip />
      <el-table-column label="年级" prop="grade">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.CMIS_GRADE_TYPE" :value="scope.row.grade" />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        prop="createTime"
        :formatter="dateFormatter"
        show-overflow-tooltip
        width="180"
      />
      <el-table-column label="操作" fixed="right" width="100">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['cmis:classes:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['cmis:classes:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 导入班级 -->
  <Dialog
    v-model="importState.dialogVisible"
    :title="importState.title"
    width="80%"
    :minHeight="900"
  >
    <ExcelParser
      :tips="importState.tips"
      ref="excelParserRef"
      :importApi="ClassesApi.importClasses"
      :targetTableColumns="importColumns"
      :templateName="importState.title"
    />
    <template #footer>
      <el-button type="primary" @click="onBatchImport()" :loading="importLoading">确 定</el-button>
      <el-button @click="onCancel">取 消</el-button>
    </template>
  </Dialog>

  <!-- 表单弹窗：添加/修改 -->
  <ClassesForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts" name="Classes">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import * as ClassesApi from '@/api/cmis/classes'
import * as SchoolApi from '@/api/cmis/school'
import * as CollegeApi from '@/api/cmis/college'
import * as MajorApi from '@/api/cmis/major'
import { DICT_TYPE, getIntDictOptions, getDictValuesStr } from '@/utils/dict'
import ClassesForm from './ClassesForm.vue'
import { ITargetTableColumbnItem } from '@/components/ExcelParser/src/type'
import { useValidator } from '@/hooks/web/useValidator'
const { required } = useValidator()
const form = ref(null)
const { width, height } = useElementSize(form)
const tableHeight = useWindowSize(78 + 76, height)
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  createTime: [],
  classesName: null,
  classesCode: null,
  schoolId: null,
  collegeId: null,
  majorId: null,
  grade: null
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const schoolList = ref([]) //学校列表
const collegeList = ref([]) //机构列表
const majorList = ref([]) //专业列表

/** 初始化 **/
onMounted(async () => {
  getList()
  // 加载学校列表
  schoolList.value = await SchoolApi.getSchoolList('')
  getCollegeList('')
  getMajorList()
})

const changeSchool = async (value: any) => {
  queryParams.collegeId = null
  queryParams.majorId = null
  getCollegeList(value)
  getMajorList()
}

const changeCollege = async () => {
  queryParams.majorId = null
  getMajorList()
}

const getCollegeList = async (schoolId: string) => {
  const res = await CollegeApi.getCollegeList({ schoolId })
  collegeList.value = res
}

const getMajorList = async () => {
  const res = await MajorApi.getMajorList({
    schoolId: queryParams.schoolId,
    collegeId: queryParams.collegeId
  })
  majorList.value = res
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ClassesApi.getClassesPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ClassesApi.deleteClasses(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ClassesApi.exportClasses(queryParams)
    download.excel(data, '班级.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const listOfIds = ref([]) //选中的设备

// 选中设备
const selectionChange = (val: any) => {
  listOfIds.value = val.map((item: any) => item.id)
}

// 批量删除操作
const handleDeleteMulti = async () => {
  if (listOfIds.value.length > 0) {
    try {
      // 批量删除的二次确认
      await message.delConfirm()
      // 发起批量删除
      await ClassesApi.batchDeleteClasses(listOfIds.value)
      message.success(t('common.delSuccess'))
      // 刷新列表
      await getList()
    } catch {}
  } else {
    message.warning(t('请选择要删除的班级!'))
  }
}

//#region 批量导入班级
const importLoading = ref(false)
const excelParserRef = ref<any>()

const importState = reactive({
  tips: ['机构名称: 可以是学校名称等', '年级编码: ' + getDictValuesStr(DICT_TYPE.CMIS_GRADE_TYPE)],
  dialogVisible: false,
  title: '导入班级'
})

const importColumns = ref<ITargetTableColumbnItem[]>([
  {
    label: '学校',
    field: 'schoolName',
    rules: [required('学校不能为空')]
  },
  {
    label: '机构名称',
    field: 'collegeName',
    rules: []
  },
  {
    label: '机构编码',
    field: 'collegeCode',
    rules: []
  },
  {
    label: '专业名称',
    field: 'majorName',
    rules: []
  },
  {
    label: '专业编码',
    field: 'majorCode',
    rules: []
  },
  {
    label: '班级名称',
    field: 'classesName',
    rules: [required('班级名称不能为空')]
  },
  {
    label: '班级编码',
    field: 'classesCode',
    rules: []
  },
  {
    label: '年级编码',
    field: 'grade',
    rules: [required('年级编码不能为空')],
    parseRule: {
      dictType: DICT_TYPE.CMIS_GRADE_TYPE
    }
  },
  {
    label: '入学年份',
    field: 'beginYear'
  }
])

//批量导入
const onOpenBatchImport = () => {
  importState.dialogVisible = true
}

const onBatchImport = async () => {
  importLoading.value = true
  const isSuccess = await excelParserRef.value?.onSubmit()
  console.log('isSuccess', isSuccess)

  if (isSuccess) {
    importLoading.value = false
    ElMessage({
      message: '导入成功',
      type: 'success',
      duration: 1000,
      onClose: () => {
        // importLoading.value = false
        importState.dialogVisible = false
        getList()
      }
    })
  } else {
    importLoading.value = false
    return
  }
  importLoading.value = false
  importState.dialogVisible = false
}

const onCancel = () => {
  importState.dialogVisible = false
  importLoading.value = false
}

//#endregion
</script>
